package principal;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Miguel
 * 
 * Query Registro de Buses
 * SELECT  t.horasalida_traslado"HORARIO SALIDA", t.horallegada_traslado"HORARIO LLEGADA",p.nombre_pasajero"NOMBRE PASAJERO",p.apellido_pasajero"APELLIDO PASAJERO",p.domicilio_pasajero"DOMICILIO PASAJERO",c.nombre_colegio"NOMBRE COLEGIO",c.direccion_colegio"DIRECCION COLEGIO"
FROM ((traslado_diario t inner join dias_semana d on t.dia_traslado = d.id_semana) INNER JOIN pasajero p ON p.rut_pasajero = t.rut_pasajero)inner join colegio c ON c.codigo_colegio = p.codigo_colegio
WHERE id_semana = '03' and patente_bus = 'llax00';
 */
public class JIFItinerarioBus extends javax.swing.JInternalFrame {

    /**
     * Creates new form ItinerarioBus
     */
    public JIFItinerarioBus() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jCBPatentes = new javax.swing.JComboBox();
        jCBDias = new javax.swing.JComboBox();
        jBReporte = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTItinerario = new javax.swing.JTable();
        jBCancelar = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        setClosable(true);
        setTitle("Itinerario de Buses");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosed(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Itinerario"));

        jLabel1.setText("Seleccione Bus:");

        jLabel2.setText("Seleccione Día:");

        jCBDias.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Lunes", "Martes", "Miercoles", "Jueves", "Viernes" }));

        jBReporte.setText("Generar");
        jBReporte.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBReporteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jBReporte)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(33, 33, 33)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jCBPatentes, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jCBDias, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(507, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jCBPatentes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jCBDias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                .addComponent(jBReporte)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Informe"));

        jTItinerario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Horario Salida", "Horario LLegada", "Nombre Pasajero", "Apellido Pasajero", "Domicilio Pasajero", "Nombre Colegio", "Dirección Colegio"
            }
        ));
        jTItinerario.setToolTipText("");
        jScrollPane1.setViewportView(jTItinerario);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1138, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 234, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                    .addContainerGap()))
        );

        jBCancelar.setText("Cancelar");
        jBCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jBCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBCancelar)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        //Cuando aparece la ventana, carga las patentes de los buses en el combobox
        try {            
            PreparedStatement pstm = JFPrincipal.con.getConnection().prepareStatement("select patente_bus from bus;");                                   
            ResultSet res = pstm.executeQuery();
            while(res.next()){         
                jCBPatentes.addItem(res.getString("patente_bus"));
            }
            res.close(); 
        }catch(SQLException e){
            System.out.println(e);
            JOptionPane.showMessageDialog(this, "No se ha podido conectar con la base de datos","Error de Datos", JOptionPane.ERROR_MESSAGE);
            this.Salir();
        }
    }//GEN-LAST:event_formComponentShown

    private void jBReporteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBReporteActionPerformed
        //Se genera el reporte de itinerario
        int dia = jCBDias.getSelectedIndex() + 1; //el indice del dia seleccionado se le suma 1 para coincidir con el id de los dias de la base de datos
        String patente= jCBPatentes.getSelectedItem().toString(); //la patente selecciona se convierte en String
        try {
            //Se hace la solicitud de los pasajeros que debe llevar en el dia indicado
            PreparedStatement pstm = JFPrincipal.con.getConnection().prepareStatement("SELECT  t.horasalida_traslado, t.horallegada_traslado,p.nombre_pasajero,p.apellido_pasajero,p.domicilio_pasajero,c.nombre_colegio,c.direccion_colegio "+
                    "FROM ((traslado_diario t inner join dias_semana d on t.dia_traslado = d.id_semana) INNER JOIN pasajero p ON p.rut_pasajero = t.rut_pasajero)inner join colegio c ON c.codigo_colegio = p.codigo_colegio "+
                    "WHERE id_semana = '"+dia+"' and patente_bus = '"+patente+"'");                             
            ResultSet res = pstm.executeQuery(); //se almacenan los resultados devueltos
            int i = 0; //contador de registros devueltos
            while(res.next()){ //se recorren los registros para tener el total
                i++;
            }
            System.out.println("numero de registros: " + i);
            res.first(); //se vuelve al primer registro
            Object[][] data = new String[i][7]; //se crea la matriz de datos para la tabla de informe
            for(int j = 0; j < i; j++) //se recorren los registros y se asignan a la matriz de datos
            {
                data[j][0] = res.getString("horasalida_traslado");            
                data[j][1] = res.getString("horallegada_traslado"); 
                data[j][2] = res.getString("nombre_pasajero"); 
                data[j][3] = res.getString("apellido_pasajero"); 
                data[j][4] = res.getString("domicilio_pasajero"); 
                data[j][5] = res.getString("nombre_colegio"); 
                data[j][6] = res.getString("direccion_colegio"); 
                res.next();
            } 
            res.close(); 
            String[] columNames = {"Horario Salida","Horario LLegada","Nombre Pasajero","Apellido Pasajero","Domicilio Pasajero","Nombre Colegio", "Direccion Colegio"}; //encabezados de la columnas de la tabla de itinerario
            //Se colocan los datos en una tabla de datos, sobreescribiendo el metodo isCellEditable
            //para que no se puedan modificar los datos manualmente
            DefaultTableModel datos = new DefaultTableModel(data,columNames){
                 @Override
                 public boolean isCellEditable(int row, int column) { return false; }
            };
            jTItinerario.setModel(datos); //se asigna la tabla de datos al modelo de la tabla de itinerario
            if (i == 0)
                JOptionPane.showMessageDialog(this, "No hay registros para el bus seleccionado en el día indicado.","Advertencia", JOptionPane.WARNING_MESSAGE);
        }catch(SQLException e){
            System.out.println(e);
            JOptionPane.showMessageDialog(this, "No se ha podido generar el itinerario.","Error de Datos", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jBReporteActionPerformed

    private void jBCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCancelarActionPerformed
        //El boton Cancelar cierra la ventana actual
        this.Salir();
    }//GEN-LAST:event_jBCancelarActionPerformed

    private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosed
        JFPrincipal.itinerario = null; //se asigna null a la variable que almacena la ventana actual
    }//GEN-LAST:event_formInternalFrameClosed

    private void Salir()
    {
        this.setVisible(false);
        this.dispose();
        JFPrincipal.itinerario = null; //se asigna null a la variable que almacena la ventana actual
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBCancelar;
    private javax.swing.JButton jBReporte;
    private javax.swing.JComboBox jCBDias;
    private javax.swing.JComboBox jCBPatentes;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTItinerario;
    // End of variables declaration//GEN-END:variables
}
